import React, { useState, useEffect, useRef } from 'react';
import { Toast, Dialog, Input, Popup, TextArea, Picker } from 'antd-mobile'
import HeadTop from '@/components/HeadTop';
import FootButton from '@/components/FootButton';
import PickerSelect from '@/components/PickerSelect';
import PickerSelectMoreDevice from '@/components/PickerSelectMoreDevice';
import UploadPhotos from '@/components/UploadPhotos';
import ScanPicker from '@/components/ScanPicker';
import { add_check_cache, decrement_check_cache, change_spot_params } from '@/Store/action';
import { connect } from 'react-redux';
import Index from '@/api/equipment';
import IndexSpot from '@/api/spotCheck';
import "./add.less"

function Add(props) {
    const [basicColumns, setbasicColumns] = useState([]);  // 设备类型
    const [basicColumnsVal, setbasicColumnsVal] = useState('');
    const [basicColumns2, setbasicColumns2] = useState([]);
    const [deviceName, setdeviceName] = useState('');
    const [deviceNo, setdeviceNo] = useState('');
    const [deviceNoParams, setdeviceNoParams] = useState("")
    const [badReason, setBadReason] = useState('');   //维修原因
    const [LocationList, setLocationList] = useState();
    const [deviceLocation, setdeviceLocation] = useState('')
    const [deviceLocationCode, setdeviceLocationCode] = useState('')
    const [line, setLine] = useState('')
    const uploadRef = useRef()
    const [visible, setVisible] = useState(false)

    const [visibleType, setVisibleType] = useState(false)
    const [value, setValue] = useState(['REPAIR'])
    const [valueTxt, setValueTxt] = useState('报修')
    const [basicColumnsType, setbasicColumnsType] = useState([])

    useEffect(() => {
        // 设备类型
        getTypeList()

        if (props.location?.state?.from == 'equipment') {

            handlePress(props.location?.state?.no)
        }

        // 点检过来
        if (props.location?.state?.from == 'spotcheck' || props.location?.state?.from == 'Inspection') {

            let detaiObj = props.location?.state?.detaiObj
            setdeviceName(detaiObj.deviceName)
            setdeviceNo(detaiObj.deviceCode)
            setdeviceNoParams(detaiObj.deviceNo)
            setbasicColumnsVal(detaiObj.deviceType)
            Index.getByDeviceCode(detaiObj.deviceCode).then(res => {
                if (res.data.code == 0) {
                    setLocationList(res.data.data)
                }
            })
        }

        // 类型字典
        getDic()

    }, [])

    const getDic = () => {
        Index.dictDetails({ dictCode: 'REPAIR_TASK_TYPE' }).then(res => {
            if (res.data.code == 0) {
                setbasicColumnsType([res.data.data.records])
            }
        })
    }

    useEffect(() => {
        if(basicColumnsType.length){
            let txt = basicColumnsType[0]?.find(el => el.value == value[0])?.label
            setValueTxt(txt)
        }
    }, [value])


    // 设备类型
    const getTypeList = () => {
        Index.getDeviceType('DEVICE_TYPE').then(res => {
            if (res.data.code == 0) {
                setbasicColumns([res.data.data])
            }
        })
    }
    useEffect(() => {
        if (basicColumnsVal) {
            getDeviceNoList()
        }
    }, [basicColumnsVal])
    


    // 设备编号
    const getDeviceNoList = () => {
        Index.getDeviceList({
            deviceType: basicColumnsVal
        }).then(res => {
            if (res.data.code == 0) {
                let arr = res.data.data.map(el => {
                    return {
                        label: el.fixedAssetsName,
                        value: el.fixedAssetsName,
                        deviceCode: el.deviceCode,
                        no: el.no,
                        deviceCode: el.deviceCode,
                        fixedAssetsName: el.fixedAssetsName,
                        deviceType: el.deviceType
                    }
                })
                setbasicColumns2([arr])
            }
        })
    }
    const setSelectVal = (type, val) => {
        if (type == '1') {
            setbasicColumnsVal(val[0])
        }
    }

    const getSubmitSure = () => {
        if (!basicColumns) {
            Toast.show({
                content: '请选择设备类型',
            })

            return
        }
        if (!basicColumns2) {
            Toast.show({
                content: '请选择设备名称',
            })

            return
        }
        if (!badReason) {
            Toast.show({
                content: '请输入故障描述',
            })

            return
        }
        if (!uploadRef.current.photoList) {
            Toast.show({
                content: '请上传故障图片',
            })

            return
        }
        if (!deviceLocation) {
            Toast.show({
                content: '请选择设备位置',
            })

            return
        }

        let txt = '确认发布维修任务'
        Dialog.confirm({
            content: txt,
            onConfirm: async () => {
                deviceAdd()
            },
        })
    }

    const submitModal = (items) => {
        setVisible(false)
        setdeviceName(items.fixedAssetsName)
        setdeviceNo(items.deviceCode)
        setdeviceNoParams(items.no)
        Index.getByDeviceCode(items.deviceCode).then(res => {
            if (res.data.code == 0) {
                setLocationList(res.data.data)
            }
        })
    }

    const deviceAdd = () => {
        let params = {
            line: line,
            deviceLocationCode: deviceLocationCode,
            deviceLocation: deviceLocation,
            repairContent: '',// repairContent,
            deviceNo: deviceNoParams, //deviceNo, //basicColumnsVal2,
            deviceName: deviceName,// o.fixedAssetsName,//deviceName,
            badReason: badReason,
            deviceType: basicColumnsVal,
            photoUrl: uploadRef.current ? uploadRef.current.photoList.join(",") : '',
            repairTaskType: value[0]
        }
        Index.deviceAdd(params).then(res => {
            if (res.data.code) {
                Toast.show({
                    content: res.data.msg
                })
                return
            }
            // 如果是点检过来
            if (props.location?.state?.from == 'spotcheck' || props.location?.state?.from == 'Inspection') {
                IndexSpot.finishInspection({
                    ...props.spotCheckParams,
                    notice: '已报修'
                }).then(res => {
                    console.log(res)
                })
            }
            Toast.show({
                content: res.data.msg,
            })

            props.history.push("/equipment")
        })
    };

    const handlePress = (code) => {
        if (!code) return
        Index.getDeviceByLocationCode(code).then(res => {
            if (res.data.code) {
                Toast.show({
                    content: res.data.msg
                })

                return
            }

            let _data = res.data.data || {}

            setbasicColumnsVal(_data.deviceType)
            setdeviceName(_data.fixedAssetsName)
            setdeviceNo(_data.deviceCode)
            setdeviceNoParams(_data.no)
            setdeviceLocationCode(_data.deviceLocationCode)
            setdeviceLocation(_data.deviceLocation)
            setLine(_data.line)
        })
    }

    const setLocationCOde = (code) => {
        setdeviceLocationCode(code[0])
        let deviceLocation = LocationList.find(el => el.locationCode == code[0])?.location
        let line = LocationList.find(el => el.locationCode == code[0])?.line
        setdeviceLocation(deviceLocation)
        setLine(line)
    }

    return (
        <div className='page-wrapper'>
            <HeadTop title="新增设备维修" history={props.history}></HeadTop>
            <div className="add-wrapper">
                <div className="list-line">
                    <span>设备类型</span>
                    <PickerSelect
                        placeholderTxt="请选择设备类型"
                        basicColumns={basicColumns}
                        defaultValue={basicColumnsVal}
                        setSelectVal={(e) => setSelectVal('1', e)}
                    ></PickerSelect>
                </div>
                <div className="list-line">
                    <span>设备名称</span>
                    <Input
                        className='bc'
                        placeholder='请选择设备名称'
                        onClick={() => setVisible(true)}
                        value={deviceName}
                    />
                </div>
                <div className="list-line">
                    <span>设备编号</span>
                    <Input
                        disabled
                        className='bc'
                        placeholder='请输入设备编号'
                        value={deviceNo}
                    />
                </div>
                <div className="list-line">
                    <span>设备位置</span>
                    <ScanPicker
                        defaultValue={deviceLocation}
                        placeholderTxt="请扫描/选择设备位置"
                        LocationList={LocationList}
                        handlePress={handlePress}
                        setLocationCOde={setLocationCOde}></ScanPicker>
                </div>
                <div className="list-line">
                    <span style={{ width: '24vw' }}>维修类型</span>
                    <span className="styleType" onClick={() => setVisibleType(true)}>{valueTxt}</span>
                </div>
                <div className="list-line flc">
                    <span>设备故障描述</span>
                    <TextArea
                        className='bc'
                        placeholder='请输入设备故障描述'
                        value={badReason}
                        onChange={val => {
                            setBadReason(val)
                        }}
                    />
                </div>
                <div className="list-line flc">
                    <span>上传故障图片</span>
                    <UploadPhotos
                        ref={uploadRef}
                        isAdd={true}
                        showUpload="REPAIRING" />
                </div>
            </div>
            <FootButton
                cancelTxt="返回"
                sureTxt='确认维修任务'
                getSubmitCancel={() => props.history.goBack(-1)}
                getSubmitSure={getSubmitSure}>
            </FootButton> :

            {/* 备件 列表 */}
            <Popup
                className='select-more-picker'
                visible={visible}
                onMaskClick={() => {
                    setVisible(false)
                }}
                bodyStyle={{ height: '60vh' }}
            >
                <PickerSelectMoreDevice
                    basicColumns2={basicColumns2}
                    close={() => setVisible(false)}
                    submit={submitModal}></PickerSelectMoreDevice>
            </Popup>

            {/* 设备类型 */}
            <Picker
                columns={basicColumnsType}
                visible={visibleType}
                onClose={() => {
                    setVisibleType(false)
                }}
                style={{
                    '--title-font-size': '20px',
                    '--header-button-font-size': '18px',
                    '--item-font-size': '18px',
                    '--item-height': '40px',
                }}
                value={value}
                onConfirm={v => {
                    setValue(v)
                }}
            />
        </div >
    );
}


const mapStateToProps = (state) => {
    return {
        checkItemsCache: state.checkItemsCache,
        username: state.username,
        spotCheckParams: state.spotCheckParams
    };
};

const mapDispatchToProps = {
    add_check_cache,
    decrement_check_cache,
    change_spot_params
};


export default connect(mapStateToProps, mapDispatchToProps)(Add);
